package com.ang.jdk8.stream;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;
import java.util.stream.IntStream;

/**
 * @author ssang
 * @date 2021-09-26 15:32
 */
public class MapList {
    public static void main(String[] args) {
        MapList m = new MapList();
        m.test01();
    }

    //使用stream().map()返回新的list，map参数接受一个函数
    public void test01(){
        List<Integer> list = new ArrayList<>();
        IntStream.range(0,10).forEach(
                i->list.add(i)
        );

        //返回一个新的list，原来的list中的元素 i*2
        List resultList = list.stream().map(i -> i*2).collect(Collectors.toList());

        resultList.stream().forEach(System.out::println);
        System.out.println("==================");
        list.stream().forEach(System.out::println);
    }


    /**
     * 使用filter过滤id>1后的User
     * 通过map()，将user的age设置为30
     */
    public void test02(){
        User u1 = new User(1,"A",0);
        User u2 = new User(2,"B",0);
        User u3 = new User(3,"C",0);

        List<User> list = Arrays.asList(u1,u2,u3);

        List<User> newList = list.stream()
            .filter(u -> {return u.id>1;})//只有一行，return可以不写
            .map(user->{
                user.age=30;
                return user;
            })
            .collect(Collectors.toList());

        newList.stream().forEach(u-> System.out.println(u.age));
    }

    /**
     * 拼接字符串
     */
    public void test03(){
        List<Integer> list = new ArrayList<>();
        IntStream.range(0,10).forEach(
                i->list.add(i)
        );

        String str = list.stream().map(l->"str"+l).collect(Collectors.joining(","));

        System.out.println(str);
    }


    //****************************************************
    //内部类
    //****************************************************
    class User{
        int id;
        String name;
        int age;

        public User(int id, String name, int age) {
            this.id = id;
            this.name = name;
            this.age = age;
        }
    }
}
